<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登入</title>
    <link rel="stylesheet" href="./resources/css/common.css">
    <link rel="stylesheet" href="./resources/css/login.css">


</head>
<body>
    <div class="login-container">
        <div class="login-dialog">
            <h3>登入</h3>
            <div class="row">
                <span>用户名</span>
                <input type="text" id="username">
            </div>
            <div class="error" id="usernameError" ></div>
            <div class="row">
                <span>密码</span>
                <input type="password" id="password">
            </div>
            <div class="error" id="passwordError" onblur="checkPassword()"></div>
            <div class="row submit-row">
                <button id="submit">登入</button>
            </div>
            <div class="link">还没有账号？<a href="register.html">注册</a></div>
        </div>
    </div>

    <script src="./resources/js/jquery.min.js"></script>

    <script>
        let usernameInput = document.querySelector('#username');
        let passwordInput = document.querySelector('#password');
        let submiButton = document.querySelector('#submit');

        function checkPassword(){
            var res = /^[0-9a-zA-Z_]{6}$/.test(passwordInput.value);
            if(!res){
                document.getElementById("passwordError").innerHTML = "密码必须为6位自然数或字母组成!";
            }else{
                document.getElementById("passwordError").innerHTML = "";
            }
        }

        submiButton.onclick = function(){
            $.ajax({
                method:'post',
                url:'/login',
                data:{
                    username:usernameInput.value,
                    password:passwordInput.value
                },
                success:function(data){
                    if(data && data.userId > 0){
                        alert("登入成功");
                        location.replace("/game_hall.html");
                    }else if(data && data.userId == -1){
                        alert("账号在别处登入！请重新登入");
                        location.replace("/login.html")
                    }else{
                        alert("登入失败！");
                    }
                }
            })
        }
    </script>

</body> 
</html>